package com.ruoyi.labdata.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.labdata.domain.LabBlackPersonnelVo;
import com.ruoyi.labdata.domain.LabBlacklist;
import com.ruoyi.labdata.domain.LabBlacklistPersonnel;
import com.ruoyi.labdata.domain.LabFile;
import com.ruoyi.labdata.domain.LabReservationParameterPersonnel;
import com.ruoyi.labdata.mapper.LabBlacklistMapper;
import com.ruoyi.labdata.mapper.LabBlacklistPersonnelMapper;
import com.ruoyi.labdata.service.ILabBlacklistService;
import com.ruoyi.labdata.service.ILabFileService;
import com.ruoyi.labdata.service.ILabReservationParameterPersonnelService;
import com.ruoyi.system.utils.FileTypeEnum;

import cn.hutool.core.util.ObjectUtil;

/**
 * 实验室黑名单基本信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-04-02
 */
@Service
public class LabBlacklistServiceImpl implements ILabBlacklistService {

    private static final String belongType = FileTypeEnum.LabBlack.getValue();

    @Resource
    private LabBlacklistMapper labBlacklistMapper;

    @Autowired
    private ILabFileService labFileService;

    @Resource
    private LabBlacklistPersonnelMapper labBlacklistPersonnelMapper;

    @Autowired
    private ILabReservationParameterPersonnelService labReservationParameterPersonnelService;

    private Logger logger = LoggerFactory.getLogger(LabBlacklistServiceImpl.class);

    /**
     * 查询实验室黑名单基本信息
     *
     * @param reservationId 实验室预约ID
     * @return 实验室黑名单基本信息
     */
    @Override
    public LabBlacklist selectLabBlacklistByReservationId(Long reservationId) {
        // 根据预约id查询黑名单基本信息
        LabBlacklist labBlacklist1 = labBlacklistMapper.selectLabBlacklistByReservationId(reservationId);
        LabBlacklist labBlacklist = labBlacklist1 == null ? new LabBlacklist():labBlacklist1;
        boolean isCommit = false;
        if(labBlacklist.getIsCommitted()!=null && labBlacklist.getIsCommitted()==1){
        	isCommit = true;
        }
        LabReservationParameterPersonnel labReservationParameterPersonnel = new LabReservationParameterPersonnel();
        labReservationParameterPersonnel.setLabReservationId(reservationId);
        //查询此次预约关联的相关人员数据
        List<LabReservationParameterPersonnel> labReservationParameterPersonnels = labReservationParameterPersonnelService.selectLabReservationParameterPersonnelList(labReservationParameterPersonnel);
        LabBlacklistPersonnel labBlacklistPersonnel = new LabBlacklistPersonnel();
        List<LabBlacklistPersonnel> labBlackPersonnelVos = new ArrayList<>();
        if (null != labBlacklist && null != labBlacklist.getBlacklistId() ){
            labBlacklistPersonnel.setBlacklistId(labBlacklist.getBlacklistId());
            // 查询此次预约加入的黑名单的人员数据
            labBlackPersonnelVos =  labBlacklistPersonnelMapper.selectLabBlacklistPersonnelList(labBlacklistPersonnel);
        }
        // 预约人员
        ArrayList<LabBlackPersonnelVo> labBlackPersonnelAppointmentVoList = new ArrayList<>();
        // 参与人员
        ArrayList<LabBlackPersonnelVo> labBlackPersonnelParticipationVoList = new ArrayList<>();
        for (LabReservationParameterPersonnel reservationParameterPersonnel : labReservationParameterPersonnels) {
            LabBlackPersonnelVo labBlackPersonnelVo = new LabBlackPersonnelVo();
            labBlackPersonnelVo.setPersonnelName(reservationParameterPersonnel.getApplicantName());
            labBlackPersonnelVo.setPersonnelId(reservationParameterPersonnel.getApplicantId());
            labBlackPersonnelVo.setType(reservationParameterPersonnel.getType());
            labBlackPersonnelVo.setPersonnelNo(reservationParameterPersonnel.getApplicantNo());
            // 设置人员是否违规
           
            for (LabBlacklistPersonnel blackPersonnelVo : labBlackPersonnelVos) {
                if (ObjectUtil.isNotEmpty(reservationParameterPersonnel.getApplicantId()) &&
                        reservationParameterPersonnel.getApplicantId().longValue()==blackPersonnelVo.getPersonnelId().longValue()){
                	labBlackPersonnelVo.setViolation(true);
                	labBlackPersonnelVo.setViolateNum(blackPersonnelVo.getViolateNum());
                   break;
                }
            }
            if(labBlackPersonnelVo.getViolation()==null){
            	if(isCommit){
            		//已经提交的只能查看已经设为黑名单 的人员.
            		continue;
            	}
	            // 查询该人员黑名单次数
	            Integer count = 0;
	            if (null != reservationParameterPersonnel.getApplicantId()){
	                count = labBlacklistPersonnelMapper.selectLabBlackListPersonnelCount(reservationParameterPersonnel.getApplicantId());
	            }
	            labBlackPersonnelVo.setViolateNum(count);
            }
            
            if ("0".equals(reservationParameterPersonnel.getType())){
                // 预约人员
                labBlackPersonnelAppointmentVoList.add(labBlackPersonnelVo);
            }else {
                // 参与人员
                labBlackPersonnelParticipationVoList.add(labBlackPersonnelVo);
            }
        }
        labBlacklist.setLabBlackPersonnelAppointmentVos(labBlackPersonnelAppointmentVoList);
        labBlacklist.setLabBlackPersonnelParticipationVos(labBlackPersonnelParticipationVoList);
        // 查询并设置黑名单图片列表信息
        if (null != labBlacklist && null != labBlacklist.getBlacklistId()){
            List<LabFile> labFiles = labFileService.getFiles(labBlacklist.getBlacklistId(), belongType);
            labBlacklist.setImages(labFiles);
        }
        return labBlacklist;
    }

    /**
     * 查询实验室黑名单基本信息列表
     *
     * @param labBlacklist 实验室黑名单基本信息
     * @return 实验室黑名单基本信息
     */
    @Override
    public List<LabBlacklist> selectLabBlacklistList(LabBlacklist labBlacklist) {
        return labBlacklistMapper.selectLabBlacklistList(labBlacklist);
    }

    /**
     * 新增实验室黑名单基本信息
     *
     * @param labBlacklist 实验室黑名单基本信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertLabBlacklist(LabBlacklist labBlacklist) {
        logger.info("-----增加黑名单信息----"+ JSON.toJSONString(labBlacklist));
        SysUser user = SecurityUtils.getLoginUser().getUser();
        boolean isCommit = labBlacklist.getIsCommitted()!=null && labBlacklist.getIsCommitted().intValue()==1;
        labBlacklist.setCreateTime(DateUtils.getNowDate());
        labBlacklist.setCreateUserId(user.getUserId());
        labBlacklist.setCreateBy(user.getNickName());
        // 保存黑名单基本信息
        int ret = labBlacklistMapper.insertLabBlacklist(labBlacklist);
        if(ret==0){
        	throw new RuntimeException("该实验室预约流程已经加过黑名单，不能再加黑名单.流程ID:"+labBlacklist.getReservationId());
        }
        List<LabBlackPersonnelVo> list = new ArrayList<>();
        List<LabBlackPersonnelVo> labBlackPersonnelAppointmentVos = labBlacklist.getLabBlackPersonnelAppointmentVos();
        List<LabBlackPersonnelVo> labBlackPersonnelParticipationVos = labBlacklist.getLabBlackPersonnelParticipationVos();
       list.addAll(labBlackPersonnelAppointmentVos);
       list.addAll(labBlackPersonnelParticipationVos);
        for (LabBlackPersonnelVo person : list) {
        	if(person.getViolation() == null || !person.getViolation()){
        		continue;
        	}
            LabBlacklistPersonnel labBlacklistPersonnel = new LabBlacklistPersonnel();
            labBlacklistPersonnel.setCreateTime(DateUtils.getNowDate());
            labBlacklistPersonnel.setCreateUserId(user.getUserId());
            labBlacklistPersonnel.setCreateBy(user.getNickName());
            //设置黑名单基本信息id
            labBlacklistPersonnel.setBlacklistId(labBlacklist.getBlacklistId());
            //设置违规人员id
            labBlacklistPersonnel.setPersonnelId(person.getPersonnelId());
            if(isCommit){
            	labBlacklistPersonnel.setViolateNum(person.getViolateNum()+1);
            }else{
            	labBlacklistPersonnel.setViolateNum(person.getViolateNum());
            }
            labBlacklistPersonnelMapper.insertLabBlacklistPersonnel(labBlacklistPersonnel);
        }
        labFileService.insertFiles(labBlacklist.getImages(), labBlacklist.getBlacklistId(), belongType);
        if(isCommit){
        	labBlacklistMapper.commitLabBlacklist(labBlacklist.getBlacklistId());
        }
        return ret;
    }

    /**
     * 修改实验室黑名单基本信息
     *
     * @param labBlacklist 实验室黑名单基本信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateLabBlacklist(LabBlacklist labBlacklist) {
        logger.info("-----修改黑名单信息----"+ JSON.toJSONString(labBlacklist));
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 修改黑名单基本信息
        int i = labBlacklistMapper.updateLabBlacklist(labBlacklist);
        if(i==0){
        	throw new RuntimeException("该实验室预约黑名单已经提交，不能再修改。");
        }
        boolean isCommit = labBlacklist.getIsCommitted()!=null && labBlacklist.getIsCommitted().intValue()==1;
        List<LabBlackPersonnelVo> list = new ArrayList<>();
        List<LabBlackPersonnelVo> labBlackPersonnelAppointmentVos = labBlacklist.getLabBlackPersonnelAppointmentVos();
        List<LabBlackPersonnelVo> labBlackPersonnelParticipationVos = labBlacklist.getLabBlackPersonnelParticipationVos();
        list.addAll(labBlackPersonnelAppointmentVos);
        list.addAll(labBlackPersonnelParticipationVos);
     
        //删除关联的黑名单关联的黑名单人员数据
        labBlacklistPersonnelMapper.deleteLabBlacklistPersonnelByBlackListId(labBlacklist.getBlacklistId());
        for (LabBlackPersonnelVo person : list) {
        	if(person.getViolation() == null || !person.getViolation()){
        		continue;
        	}
            LabBlacklistPersonnel labBlacklistPersonnel = new LabBlacklistPersonnel();
            labBlacklistPersonnel.setCreateTime(DateUtils.getNowDate());
            labBlacklistPersonnel.setCreateUserId(user.getUserId());
            labBlacklistPersonnel.setCreateBy(user.getNickName());
            //设置黑名单基本信息id
            labBlacklistPersonnel.setBlacklistId(labBlacklist.getBlacklistId());
            //设置违规人员id
            labBlacklistPersonnel.setPersonnelId(person.getPersonnelId());
            if(isCommit){
            	labBlacklistPersonnel.setViolateNum(person.getViolateNum()+1);
            }else{
            	labBlacklistPersonnel.setViolateNum(person.getViolateNum());
            }
            labBlacklistPersonnelMapper.insertLabBlacklistPersonnel(labBlacklistPersonnel);
        }
        labFileService.updateFiles(labBlacklist.getImages(), labBlacklist.getBlacklistId(), belongType);
        if(isCommit){
        	labBlacklistMapper.commitLabBlacklist(labBlacklist.getBlacklistId());
        }
        return i;
    }

    /**
     * 批量删除实验室黑名单基本信息
     *
     * @param blacklistIds 需要删除的实验室黑名单基本信息ID
     * @return 结果
     */
    @Override
    public int deleteLabBlacklistByIds(Long[] blacklistIds) {
        return labBlacklistMapper.deleteLabBlacklistByIds(blacklistIds);
    }

    /**
     * 删除实验室黑名单基本信息信息
     *
     * @param blacklistId 实验室黑名单基本信息ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteLabBlacklistById(Long blacklistId) {
        //删除关联的黑名单关联的黑名单人员数据
        labBlacklistPersonnelMapper.deleteLabBlacklistPersonnelByBlackListId(blacklistId);
        labFileService.deleteLabFile(blacklistId, belongType);
        return labBlacklistMapper.deleteLabBlacklistById(blacklistId);
    }

	@Override
	public List<LabBlacklist> queryLabBlackUserList(LabBlacklist labBlacklist) {
		return this.labBlacklistMapper.queryLabBlackUserList(labBlacklist);
	}
	
	public LabBlacklist getLabBlackUserById(Long userBlackId){
		LabBlacklist userBack = labBlacklistMapper.getLabBlackUserById(userBlackId);
		List<LabFile> labFiles = labFileService.getFiles(userBack.getBlacklistId(), belongType);
		userBack.setImages(labFiles);
		return userBack;
	}
    
    
}
